<script lang="ts" setup>
import type { VxeTableGridOptions } from '@vben/plugins/vxe-table'

import { computed, h, ref } from 'vue'

import { Page, useVbenModal } from '@vben/common-ui'

import { useDebounceFn } from '@vueuse/core'
import { Button, Col, Divider, InputNumber, message, Row, Select, Space, Spin, Switch, Tag } from 'ant-design-vue'

import adapterFileLists from '#/adapter/component/FileManage/updataFile.vue'
import { useVbenForm } from '#/adapter/form'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { getUserBaseApi } from '#/api'
import {
  allIndex,
  colorAll,
  colorSeriesTree,
  DictAddInit,
  ErpBrandList,
  fastAdd,
  fastEdit,
  getAttachFiled,
  getFactoryIndex,
  getGoodsStyleCategory,
  getSizeGroupList,
  getTreeAll,
  queryDefaultRfidOptions,
  ScmGoodsAdd,
  ScmGoodsEdit,
  ScmGoodsInfo,
  userCategorys,
} from '#/api/goods'
import { toCascaderOptions } from '#/utils'
import submitApproval from '#/views/backend/modules/submitApproval.vue'

import FileList from './fileList.vue'
import ImageUploader from './imageUploader.vue'

const emit = defineEmits(['refresh'])
const isEdit: any = ref<boolean>(false)
const currentView = ref<string>('edit') // 新增变量存储当前视图类型
const keyword1 = ref('')
const keyword2 = ref('')
const keyword3 = ref('')
const keyword5 = ref('')
const attrKeys = ref([])
const fetching = ref(false)
const ingrImages = ref<any>(null) // 检测文件
const goodsImages = ref<any>(null) // 成品图片
const p__plan_total_num = ref<any>(null) // 检测文件
const categorysList = ref([]) // 检测文件

const upCongfig: any = ref() // 货品图片数组

function onSubmit(values: Record<string, any>) {
  message.success({
    content: `form values: ${JSON.stringify(values)}`,
  })
}

// 字典下来数据
const selectFieldsKeys = [
  'buyerUsers',
  'merchUsers',
  'unevenColor',
  'thickness',
  'pattern',
  'ageName',
  'factionName',
  'warmColor',
  'colorSystem',
  'categoryLifecycle',
  'singleLifecycle',
  'displayFunds',
  'securityCategory',
  'execStandard',
  'pattern',
  'priceRange',
  'goodsRules',
  'tagVersion',
  'secondStyle',
  'designUser',
  'planningStyle',
  'goodsSex',
]
/**
 * 获取颜色远程选项
 */
async function fetchColorOptions({ keyword = '' }: Record<string, any>) {
  const { list } = await colorAll({
    quick_search: keyword,
    page: 1,
    limit: 999,
    initKey: 'color.id',
    initValue: undefined,
    select: true,
  })
  return list.map((item: any) => ({
    label: item.name,
    value: item.id,
    disabled: item.is_enabled,
  }))
}
/**
 * 获取品牌远程选项
 */
async function fetchBandOptions({ keyword = '' }: Record<string, any>) {
  const { list } = await ErpBrandList({
    quick_search: keyword,
    page: 1,
    limit: 999,
    initKey: 'erp_brand_info.id',
    initValue: undefined,
    select: true,
  })
  return list.map((item: any) => ({
    label: item.title_chinese,
    value: item.id,
  }))
}

async function fetchGoodsStyleCategory({ keyword = '' }: Record<string, any>) {
  const { list } = await getGoodsStyleCategory({
    quick_search: keyword,
    page: 1,
    limit: 999,
    initKey: 'id',
    initValue: undefined,
    select: true,
  })
  return list.map((item: any) => ({
    label: item.style_category_name,
    value: item.id,
  }))
}

const selectBaseList = ref<Record<string, any>>({})
const selectSizeGroupList: any = ref() // 字典
const idsArr: any = ref([])
const categoryOptions = ref([]) // 货品分类树
const timeCategoryOptions = ref([]) // 货品波段树
const colorSeries: any = ref([]) // 色系树
const is_price_checking = ref(false)
// 获取字典
function getBaseList(arr?: any) {
  const param = {
    keys: selectFieldsKeys,
    cate_arr: arr,
  }
  DictAddInit(param).then(({ select_list }) => {
    // 需要转成数组的字段
    const keys = selectFieldsKeys
    // 统一处理
    selectBaseList.value = {
      ...select_list,
      ...Object.fromEntries(
        keys.map((k) => [
          k,
          Object.entries(select_list?.[k] || {}).map(([value, label]) => ({
            label,
            value,
          })),
        ]),
      ),
    }
  })
}

const buyerOptions = computed(() => selectBaseList.value.buyerUsers || [])
const merchUsersOptions = computed(() => selectBaseList.value.merchUsers || [])
const designUserOptions = computed(() => selectBaseList.value.designUser || [])
const planningStyleOptions = computed(() => selectBaseList.value.planningStyle || [])
const goodsRulesOptions = computed(() => selectBaseList.value.goodsRules || [])
const tagVersionOptions = computed(() => selectBaseList.value.tagVersion || [])
const selectSizeGroupOptions = computed(() => selectSizeGroupList.value || [])
const secondStyleOptions = computed(() => selectBaseList.value.secondStyle || [])
const ageNameOptions = computed(() => selectBaseList.value.ageName || [])
const patternOptions = computed(() => selectBaseList.value.pattern || [])
const thicknessOptions = computed(() => selectBaseList.value.thickness || [])
const priceRangeOptions = computed(() => selectBaseList.value.priceRange || [])
const factionNameOptions = computed(() => selectBaseList.value.factionName || [])
const execStandardOptions = computed(() => selectBaseList.value.execStandard || [])
const securityCategoryOptions = computed(() => selectBaseList.value.securityCategory || [])
const singleLifecycleOptions = computed(() => selectBaseList.value.singleLifecycle || [])
const categoryLifecycleOptions = computed(() => selectBaseList.value.categoryLifecycle || [])
const displayFundsOptions = computed(() => selectBaseList.value.displayFunds || [])
const goodsSexOptions = computed(() => selectBaseList.value.goodsSex || [])

// 获取尺码
function getSizeGroup(category?: any) {
  const param = {
    category_id: category,
  }
  getSizeGroupList(param).then((response) => {
    selectSizeGroupList.value = response.list.map((item: any) => ({
      label: item.name,
      value: item.id,
    }))
  })
}

const Text: any = computed(() => {
  return idsArr.value.length > 1 ? '保存并编辑下一项' : '保存'
})

const [Modal, modalApi] = useVbenModal({
  destroyOnClose: true,
  confirmText: Text,
  fullscreen: true,
  appendToMain: true,
  onCancel() {
    modalApi.close()
  },
  async onConfirm() {
    save()
  },
  onOpenChange: async (isOpen: boolean) => {
    if (!isOpen) return
    // 1. 先并行拉取级联数据
    const [cateRes, timeRes, colors, userCate] = await Promise.all([
      allIndex(),
      getTreeAll(),
      colorSeriesTree(),
      userCategorys({
        limit: 30,
        is_remote: true,
        page: 1,
        select: true,
      }),
    ])
    categoryOptions.value = cateRes.list
    timeCategoryOptions.value = timeRes
    colorSeries.value = toCascaderOptions(colors.list)
    categorysList.value = userCate.list.map((item: any) => ({
      label: item.name,
      value: item.id,
    }))
    handleSupplySearch('')
    // 2. 处理编辑回显
    const { ids, view, purchase_detail_id } = modalApi.getData<Record<string, any>>()
    currentView.value = view || 'edit' // 保存当前视图类型
    if (Array.isArray(ids)) {
      // 如果是多个编辑
      idsArr.value = ids
      initData(ids[0])
      // 过滤掉data_type字段
      // schema.value = schema.value.filter((item) => item.fieldName !== 'data_type')
    } else {
      if (ids) {
        if (view === 'edit') {
          initData(ids, purchase_detail_id)
          // schema.value = schema.value.filter((item) => item.fieldName !== 'data_type')
        } else {
          await initData(ids, purchase_detail_id)
          // await baseFormApi.setValues({ goods_rules: '标准规则AB款' }, false);
        }
      } else {
        // 新建
        await baseFormApi.setValues({ erp_brand_id: 42 }, false)
        await baseFormApi.setValues({ goods_nature: ['1'] }, false)
        await baseFormApi.setValues({ sex: '男' }, false)
        await baseFormApi.setValues({ rfid_check: 0 }, false)
        await baseFormApi.setValues({ gram_weight: 0 }, false)
        await baseFormApi.setValues({ has_ail: 0 }, false)
        await baseFormApi.setValues({ goods_rules: '标准规则新款' }, false)

        handleAdd()
        getBaseList()
      }
    }
    isEdit.value = view === 'edit'
  },
})
// 保存方法
async function save() {
  const { valid } = await baseFormApi.validate()
  if (!valid) return
  // 提取所有URL并清理格式
  const urls = goodsImages.value
    ?.map((item: any) => {
      if (item.url) {
        // 清理URL中的反引号和空格
        return item.url.replaceAll(/[`\s]/g, '')
      }
      return ''
    })
    .filter(Boolean) // 过滤掉空字符串
  if (urls && urls.length > 0) {
    baseFormApi.setValues({
      goods_images: urls,
    })
  }
  const tableData = gridApi.grid.getData()
  const values = await baseFormApi.getValues()
  values.supply_list = tableData
  values.attr_json = attrKeys.value.reduce((acc, key) => {
    if (values[key] !== undefined) {
      acc[key] = values[key]
    }
    return acc
  }, {})
  const hideLoading = message.loading({
    content: `正在保存`,
    duration: 1,
  })
  modalApi.lock(true)
  if (isEdit.value) {
    // 如果是多个编辑
    if (idsArr.value && idsArr.value.length > 1) {
      // 先保存当前简码
      const param = {
        formData: {
          template_id: values.template_id,
          template_no: values.template_no,
        },
      }
      fastEdit(param).then((res: any) => {
        if (res.data.code === 1) {
          ScmGoodsEdit(values)
            .then((res: any) => {
              if (res.data.code === 201) {
                message.error({
                  content: res.data.msg,
                })
                submitApprovalModalApi.setData({ data: res.data.data }).open()
                hideLoading()
                modalApi.unlock()
              } else if (res.data.code === 1) {
                message.success({
                  content: `保存成功`,
                })
                emit('refresh')
                modalApi.unlock()
                // 删除当前保存好的项目id, 请求下一个id
                const goods_id = values.goods_id
                const index = idsArr.value.indexOf(goods_id)
                // 如果找到了对应的值，使用 splice 删除它
                if (index !== -1) {
                  idsArr.value.splice(index, 1)
                  initData(idsArr.value[0])
                }
              } else {
                message.error({
                  content: res.data.msg,
                })
              }
            })
            .catch(() => {
              modalApi.unlock()
            })
        } else {
          message.error({
            content: res.data.msg,
          })
          hideLoading()
          modalApi.unlock()
        }
      })
    } else {
      // 单个编辑
      const param = {
        formData: {
          template_id: values.template_id,
          template_no: values.template_no,
        },
      }
      fastEdit(param).then((res: any) => {
        if (res.data.code === 1) {
          ScmGoodsEdit(values)
            .then((res: any) => {
              modalApi.unlock()
              if (res.data.code === 201) {
                message.error({
                  content: res.data.msg,
                })
                submitApprovalModalApi.setData({ data: res.data.data }).open()
                hideLoading()
              } else if (res.data.code === 1) {
                emit('refresh')
                message.success({
                  content: `保存成功`,
                })
                hideLoading()
                modalApi.unlock()
                modalApi.close()
              } else {
                message.error({
                  content: res.data.msg,
                })
              }
            })
            .catch(() => {
              modalApi.unlock()
              hideLoading()
            })
        } else {
          message.error({
            content: res.data.msg,
          })
          hideLoading()
          modalApi.unlock()
        }
      })
    }
  } else {
    const parmas = {
      formData: {
        category_id_one: values.category_id[0],
        template_no: values.template_no,
        data_type: values.data_type,
      },
    }
    fastAdd(parmas).then((res: any) => {
      modalApi.unlock()
      if (res.data.code === 1) {
        values.is_spzg = true
        values.template_id = res.data.data
        ScmGoodsAdd(values)
          .then((res: any) => {
            if (res.data.code === 1) {
              message.success({
                content: `添加成功`,
              })
              emit('refresh')
              modalApi.unlock()
              hideLoading()
              modalApi.close()
            } else {
              message.error({
                content: res.data.msg,
              })
            }
          })
          .catch(() => {
            modalApi.unlock()
            hideLoading()
          })
      } else {
        message.error(res.data.msg)
      }
    })
  }
}

function convertToNormalObject(data: any) {
  const result = {}
  for (const key in data) {
    if (data.hasOwnProperty(key)) {
      const item = data[key]
      // 确保 attr_key 和 value 都存在
      if (item && item.attr_key !== undefined && item.value !== undefined) {
        result[item.attr_key] = item.value
      }
    }
  }
  return result
}

async function initData(id: any, purchase_detail_id?: string) {
  modalApi.lock()
  const { row } = await ScmGoodsInfo({
    goods_id: id,
    goods_purchase_detail_id: purchase_detail_id,
  })
  if (row) {
    modalApi.unlock()
  }
  const attrJsonObject = JSON.parse(row.attr_json)
  const attr_json = convertToNormalObject(attrJsonObject)
  const dt = { ...row, ...attr_json }
  await baseFormApi.setValues(dt, false)
  keyword1.value = `initValue:${row.template_id}`
  is_price_checking.value = row.is_price_checking
  p__plan_total_num.value = row.p__plan_total_num
  ingrImages.value = row.ingr_images || []
  existingImages.value = row.ingr_images || []
  goodsImages.value = row.goods_images || []
  gridApi.setGridOptions({ data: row.supply_list || [] })
  // 如果是拷贝 清空价格信息
  if (currentView.value === 'copy') {
    baseFormApi.setValues({ purchase_price: 0 }, false)
    baseFormApi.setValues({ direct_price: 0 }, false)
    baseFormApi.setValues({ estimated_cost: 0 }, false)
    baseFormApi.setValues({ current_settle_price: 0 }, false)
  }

  // 获取动态字段
  handleAdd(row.category_id, purchase_detail_id)
  // 获取字典
  getBaseList(row.category_id)
  // 获取尺码组
  getSizeGroup(row.category_id)

  const { siteConfig } = await getUserBaseApi()
  upCongfig.value = siteConfig
}
async function changeCategory(value: any) {
  queryDefaultRfidOptions({ cateIdStrList: [value.join(',')] }).then(async (res: any) => {
    const data = res.data.data[value.join(',')]
    const form = await baseFormApi.getValues()
    if (!form.goods_rules) {
      baseFormApi.setValues({ goods_rules: data.goodsRules }, false)
    }
    baseFormApi.setValues({ is_rfid: data.isRfid }, false)
    baseFormApi.setValues({ tag_version: data.tagVersion }, false)
    baseFormApi.setValues({ has_ail: data.hasAil }, false)
  })
  // const CategoryOne = value[0]
  // const CategoryTwo = value[1]
  // const CategoryThree = value[2]
  //
  // await ([260, 262, 263, 264].includes(CategoryOne) ? baseFormApi.setValues({ is_rfid: 1 }, false) : baseFormApi.setValues({ is_rfid: 0 }, false))
  // // a.三级分类包含牛仔的品类，新建默认吊牌版本号：合格证-45x100-水洗产品
  // const niuzai = new Set([341, 342, 343, 344, 345, 510, 585, 638, 785, 793, 831, 832, 871, 891])
  // if (niuzai.has(CategoryThree)) {
  //   await baseFormApi.setValues({ tag_version: '合格证-45x100-水洗产品' }, false)
  // }
  // // b.大类为下装、外套、内搭、人事物料 新建默认吊牌版本号：合格证-45x100 排除掉里面的牛仔
  // if ([93, 260, 262, 263, 882].includes(CategoryOne) && !niuzai.has(CategoryThree)) {
  //   await baseFormApi.setValues({ tag_version: '合格证-45x100' }, false)
  // }
  //
  // // c.大类为鞋履 、物料 新建默认吊牌版本号：合格证-35x65
  // if ([6, 264].includes(CategoryOne) && !niuzai.has(CategoryThree)) {
  //   await baseFormApi.setValues({ tag_version: '合格证-35x65' }, false)
  // }
  //
  // // d.大类配饰：新建默认吊牌版本号：合格证-35x65，注：（配饰/袜子 、配饰/内裤 配饰/眼镜 ） 新建默认吊牌版本号： 贴纸-50x38
  // const erji = new Set([281, 498, 562])
  // if ([261].includes(CategoryOne) && !erji.has(CategoryTwo)) {
  //   await baseFormApi.setValues({ tag_version: '合格证-35x65' }, false)
  // } else if ([261].includes(CategoryOne) && erji.has(CategoryTwo)) {
  //   await baseFormApi.setValues({ tag_version: '贴纸-50x38' }, false)
  // }
  // // e.大类为助销品：新建默认吊牌版本号：合格证-50x38
  // if ([9].includes(CategoryOne)) {
  //   await baseFormApi.setValues({ tag_version: '贴纸-50x38' }, false)
  // }
}

const schema = ref([
  {
    component: '',
    fieldName: '_divider2',
    formItemClass: 'col-span-4',
    hideLabel: true,
  },
  {
    component: 'Cascader',
    fieldName: 'category_id',
    label: '分类',
    rules: 'required',
    componentProps: {
      options: categoryOptions,
      placeholder: '请选择',
      showSearch: true,
      allowClear: true,
      onChange: (value: any) => {
        getSizeGroup(value)
        getBaseList(value)
        handleAdd(value)
        changeCategory(value)
      },
    },
  },
  {
    component: 'Cascader',
    fieldName: 'bd_id',
    label: '波段',
    rules: 'required',
    componentProps: {
      options: timeCategoryOptions,
      placeholder: '请选择',
      showSearch: true,
      allowClear: true,
    },
  },
  {
    component: 'Select',
    fieldName: 'size_group_id',
    label: '尺码组',
    rules: 'required',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      options: selectSizeGroupOptions,
      showSearch: true,
    },
  },
  {
    component: 'ApiSelect',
    componentProps: () => {
      return {
        api: fetchGoodsStyleCategory,
        // 禁止本地过滤
        filterOption: false,
        notFoundContent: fetching.value ? undefined : null,
        // 搜索词变化时记录下来， 使用useDebounceFn防抖。
        onSearch: useDebounceFn((value: string) => {
          keyword5.value = value
        }, 300),
        // 远程搜索参数。当搜索词变化时，params也会更新
        params: {
          keyword: keyword5.value || undefined,
        },
        showSearch: true,
        allowClear: true,
        onChange: (value: any) => {
          // if(value){
          //
          // }
        },
      }
    },
    fieldName: 'one_style_id',
    label: '一级风格',
    rules: 'required',
    renderComponentContent: () => {
      return {
        notFoundContent: fetching.value ? h(Spin) : undefined,
      }
    },
  },
  {
    component: 'Select',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      options: [
        {
          label: '引流款',
          value: 1,
        },
        {
          label: '基本款',
          value: 2,
        },
      ],
      showSearch: true,
    },
    fieldName: 'three_style_id',
    rules: 'required',
    label: '风格',
  },
  {
    component: 'Select',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      options: secondStyleOptions,
      showSearch: true,
    },
    fieldName: 'second_style',
    rules: 'required',
    label: '二级风格',
  },
  {
    component: '',
    fieldName: '_divider',
    formItemClass: 'col-span-4',
    hideLabel: true,
  },
  {
    component: 'Input',
    // 对应组件的参数
    // 字段名
    fieldName: 'template_no',
    // 界面显示的label
    label: '简码',
    rules: 'required',
  },
  {
    component: 'Select',
    fieldName: 'data_type',
    label: '归属品类(群)',
    rules: 'required',
    componentProps: {
      allowClear: true,
      options: categorysList,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      showSearch: true,
    },
  },
  {
    component: 'ApiSelect',
    disabled: isEdit,
    componentProps: () => {
      return {
        api: fetchColorOptions,
        // 禁止本地过滤
        filterOption: false,
        notFoundContent: fetching.value ? undefined : null,
        // 搜索词变化时记录下来， 使用useDebounceFn防抖。
        onSearch: useDebounceFn((value: string) => {
          keyword2.value = value
        }, 300),
        // 远程搜索参数。当搜索词变化时，params也会更新
        params: {
          keyword: keyword2.value || undefined,
        },
        showSearch: true,
        allowClear: true,
      }
    },
    fieldName: 'color_id',
    label: '颜色',
    rules: 'required',
    renderComponentContent: () => {
      return {
        notFoundContent: fetching.value ? h(Spin) : undefined,
      }
    },
  },

  {
    component: 'Select',
    fieldName: 'buyer',
    label: '买手',
    rules: 'required',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      options: buyerOptions,
      showSearch: true,
    },
  },
  {
    component: 'Select',
    fieldName: 'merchandiser',
    label: '跟单人',
    rules: 'required',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      options: merchUsersOptions,
      showSearch: true,
    },
  },
  {
    component: 'Input',
    fieldName: 'goods_name',
    label: '品名',
    help: '输入:以输入为准；空:根据分类自动生成',
    componentProps: {
      allowClear: true,
    },
  },
  {
    component: 'ApiSelect',
    componentProps: () => {
      return {
        api: fetchBandOptions,
        // 禁止本地过滤
        filterOption: false,
        notFoundContent: fetching.value ? undefined : null,
        // 搜索词变化时记录下来， 使用useDebounceFn防抖。
        onSearch: useDebounceFn((value: string) => {
          keyword3.value = value
        }, 300),
        // 远程搜索参数。当搜索词变化时，params也会更新
        params: {
          keyword: keyword3.value || undefined,
        },
        showSearch: true,
        allowClear: true,
      }
    },
    fieldName: 'erp_brand_id',
    label: '品牌',
    rules: 'required',
    renderComponentContent: () => {
      return {
        notFoundContent: fetching.value ? h(Spin) : undefined,
      }
    },
  },
  {
    component: 'Select',
    fieldName: 'goods_nature',
    label: '货品属性',
    rules: 'required',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      mode: 'multiple',
      options: [
        {
          label: '成品',
          value: '1',
        },
        {
          label: '赠品',
          value: '2',
        },
        {
          label: '礼品',
          value: '3',
        },
      ],
      showSearch: true,
    },
  },
  {
    component: 'Input',
    disabled: isEdit,
    componentProps: {
      placeholder: '空，自动生成',

      allowClear: true,
    },
    fieldName: 'goods_no',
    label: '货号',
    help: '空，自动生成',
  },

  {
    component: 'Select',
    fieldName: 'design_user',
    label: '设计师',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      options: designUserOptions,
      showSearch: true,
    },
  },
  {
    component: 'Select',
    fieldName: 'planning_style',
    label: '企划风格',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      options: planningStyleOptions,
      showSearch: true,
    },
  },
  {
    component: '',
    label: '货品图片',
    formItemClass: 'col-span-2 col-start-1',
    fieldName: 'goods_images',
  },
  {
    component: '',
    fieldName: 'ingr_images',
    formItemClass: 'col-span-2',
    label: '成分检测',
  },
  {
    component: '',
    fieldName: 'warehouse',
    formItemClass: 'col-span-4',
    hideLabel: true,
  },
  {
    component: '',
    fieldName: 'compartment',
    formItemClass: 'col-span-2',
    hideLabel: true,
  },
  {
    component: '',
    fieldName: 'Store',
    formItemClass: 'col-span-2',
    hideLabel: true,
  },
  {
    component: '',
    fieldName: '_divider1',
    formItemClass: 'col-span-4',
    hideLabel: true,
  },
  {
    component: 'Select',
    fieldName: 'goods_rules',
    label: '货号规则',
    rules: 'required',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      showSearch: true,
      options: goodsRulesOptions,
    },
  },
  {
    component: 'Select',
    fieldName: 'is_rfid',
    label: '是否RFID货品',
    rules: 'required',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      options: [
        {
          label: '是',
          value: 1,
        },
        {
          label: '否',
          value: 0,
        },
      ],
      showSearch: true,
    },
  },
  {
    component: 'Select',
    fieldName: 'has_ail',
    label: 'RFID干扰材质',
    rules: 'required',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      options: [
        {
          label: '是',
          value: 1,
        },
        {
          label: '否',
          value: 0,
        },
      ],
      showSearch: true,
    },
  },
  {
    component: 'Select',
    fieldName: 'tag_version',
    label: '吊牌版本号',
    rules: 'required',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      showSearch: true,
      options: tagVersionOptions,
    },
  },
  {
    component: 'Select',
    fieldName: 'rfid_check',
    label: '启用RFID盘点',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      options: [
        {
          label: '是',
          value: 1,
        },
        {
          label: '否',
          value: 0,
        },
      ],
      showSearch: true,
    },
  },

  {
    component: '',
    fieldName: '_divider3',
    formItemClass: 'col-span-4',
    hideLabel: true,
  },
  {
    component: 'InputNumber',
    fieldName: 'sale_price',
    label: '零售价',
    componentProps: () => ({
      disabled: is_price_checking.value,
      min: 0,
      precision: 2,
      step: 1,
      stringMode: false,
      onChange: async (value) => {
        if (value !== undefined) {
          await baseFormApi.setValues({ tag_price: Number(value) * 2 })
        }
      },
    }),
  },
  {
    component: 'InputNumber',
    fieldName: 'inventory_claim_price',
    label: '盘点赔付价',
    componentProps: () => ({
      disabled: is_price_checking.value,
      min: 0,
      precision: 2,
      step: 1,
      stringMode: false,
    }),
  },
  {
    component: 'InputNumber',
    fieldName: 'return_price',
    label: '退货价',
    componentProps: () => ({
      disabled: is_price_checking.value,
      min: 0,
      precision: 2,
      step: 1,
      stringMode: false,
    }),
  },
  {
    component: 'InputNumber',
    fieldName: 'tag_price',
    disabled: true,
    label: '吊牌价',
    componentProps: {
      min: 0,
      precision: 2,
      step: 1,
      stringMode: false,
    },
  },
  {
    component: 'InputNumber',
    fieldName: 'weight_price',
    label: '加权单价',
    componentProps: () => ({
      disabled: is_price_checking.value,
      min: 0,
      precision: 2,
      step: 1,
      stringMode: false,
    }),
  },
  {
    component: 'InputNumber',
    fieldName: 'purchase_price',
    label: '采购价',
    disabled: true,
    help: '自动获取默认的供货商的采购价',
    componentProps: {
      min: 0,
      precision: 2,
      step: 1,
      stringMode: false,
    },
  },
  {
    component: 'InputNumber',
    fieldName: 'direct_price',
    label: '直营配货价',
    disabled: true,
    componentProps: {
      min: 0,
      precision: 2,
      step: 1,
      stringMode: false,
    },
  },
  {
    component: 'InputNumber',
    fieldName: 'estimated_cost',
    disabled: true,
    label: '成本价',
    componentProps: {
      min: 0,
      precision: 2,
      step: 1,
      stringMode: false,
    },
  },
  {
    component: 'InputNumber',
    fieldName: 'current_settle_price',
    disabled: true,
    label: '当前结算价',
    componentProps: {
      min: 0,
      precision: 2,
      step: 1,
      stringMode: false,
    },
  },
  {
    component: 'InputNumber',
    fieldName: 'distribution_price',
    label: '分销价',
    help: '加盟配货价',
    componentProps: () => ({
      disabled: is_price_checking.value,
      min: 0,
      precision: 2,
      step: 1,
      stringMode: false,
    }),
  },
  {
    component: 'InputNumber',
    fieldName: 'distribution_price_history',
    label: '历史分销价',
    componentProps: () => ({
      disabled: is_price_checking.value,
      min: 0,
      precision: 2,
      step: 1,
      stringMode: false,
    }),
  },
  {
    component: 'InputNumber',
    fieldName: 'wholesale_price',
    label: '批发价',
    componentProps: () => ({
      disabled: is_price_checking.value,
      min: 0,
      precision: 2,
      step: 1,
      stringMode: false,
    }),
  },
  {
    component: '',
    fieldName: '_divider4',
    formItemClass: 'col-span-4',
    hideLabel: true,
  },
  {
    component: '',
    fieldName: 'but',
    formItemClass: 'col-span-4',
    hideLabel: true,
  },
  {
    component: '',
    fieldName: '_divider5',
    formItemClass: 'col-span-4',
    hideLabel: true,
  },
  {
    component: 'Cascader',
    fieldName: 'color_series_id',
    label: '色系',
    help: '色系、色感、深浅色',
    componentProps: {
      options: colorSeries,
      placeholder: '请选择',
      showSearch: true,
      allowClear: true,
    },
  },
  {
    component: 'Select',
    rules: 'required',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      options: ageNameOptions,
      showSearch: true,
    },
    fieldName: 'age_name',
    label: '适龄段',
  },
  {
    component: 'Select',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      options: patternOptions,
      showSearch: true,
    },
    fieldName: 'template_type',
    label: '版型',
  },
  {
    component: 'Select',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      options: thicknessOptions,
      showSearch: true,
    },
    fieldName: 'thickness',
    label: '厚薄度',
  },
  {
    component: 'Select',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      options: factionNameOptions,
      showSearch: true,
    },
    fieldName: 'faction_name',
    label: '时尚度',
  },
  {
    component: 'Select',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      options: displayFundsOptions,
      showSearch: true,
    },
    fieldName: 'display_funds',
    label: '陈列款',
  },
  {
    component: 'InputNumber',
    fieldName: 'gram_weight',
    label: '克重',
    rules: 'required',
    help: '称重标准:\n' + '外套180\n' + '裤子32\n' + '内搭52\n' + 'XL码',
    componentProps: {
      min: 0,
      precision: 2,
      step: 1,
      stringMode: false,
    },
  },
  {
    component: 'Select',
    rules: 'required',
    componentProps: {
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      options: goodsSexOptions,
    },
    fieldName: 'sex',
    label: '性别',
  },

  {
    component: 'Select',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      options: priceRangeOptions,
      showSearch: true,
    },
    fieldName: 'price_range',
    label: '价格带',
  },

  {
    component: 'Select',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      options: execStandardOptions,
      showSearch: true,
    },
    fieldName: 'exec_standard',
    label: '执行标准',
  },
  {
    component: 'Select',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      options: securityCategoryOptions,
      showSearch: true,
    },
    fieldName: 'security_category',
    label: '安全类别',
  },
  {
    component: 'Select',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      options: singleLifecycleOptions,
      showSearch: true,
    },
    fieldName: 'single_lifecycle',
    label: '单款销售生命周期',
  },
  {
    component: 'Select',
    componentProps: {
      allowClear: true,
      filterOption: (input, option) => {
        return (option?.label || '').toLowerCase().includes(input.toLowerCase())
      },
      options: categoryLifecycleOptions,
      showSearch: true,
    },
    fieldName: 'category_lifecycle',
    label: '品类生命周期(天)',
  },
  {
    component: 'Input',
    componentProps: {
      allowClear: true,
      class: 'w-full',
      showSearch: true,
    },
    fieldName: 'grade',
    label: '等级',
  },
  {
    component: 'Textarea',
    componentProps: {
      allowClear: true,
      class: 'w-full',
      showSearch: true,
    },
    fieldName: 'similar',
    label: '类似款',
  },
  {
    component: 'Textarea',
    componentProps: {
      allowClear: true,
      class: 'w-full',
      showSearch: true,
    },
    fieldName: 'shipping_remark',
    label: '铺货备注',
  },
  {
    component: 'Textarea',
    componentProps: {
      allowClear: true,
      class: 'w-full',

      showSearch: true,
    },
    fieldName: 'window_level_remark',
    label: '窗口等级备注',
  },
  {
    component: 'Textarea',
    componentProps: {
      allowClear: true,
      class: 'w-full',
      showSearch: true,
      disabled: true,
    },
    fieldName: 'use_shop_level',
    label: '店铺等级',
  },
  {
    component: 'Textarea',
    componentProps: {
      allowClear: true,
      class: 'w-full',
      showSearch: true,
    },
    fieldName: 'paving_area',
    label: '铺货区域',
  },
  {
    component: 'Textarea',
    componentProps: {
      allowClear: true,
      class: 'w-full',
      showSearch: true,
    },
    fieldName: 'selling_point',
    label: '卖点',
  },
])

const [BaseForm, baseFormApi] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  showDefaultActions: false,
  commonConfig: {
    // 在label后显示一个冒号
    colon: true,
    // 所有表单项
    componentProps: {
      class: 'w-4/5',
    },
  },
  // 提交函数
  handleSubmit: onSubmit,
  layout: 'horizontal',
  schema: [],
  wrapperClass: 'grid-cols-4',
})
function handleAdd(category?: [], id?: any) {
  const parmast = {
    attrJson: [],
    category,
    id,
  }
  let from = []
  getAttachFiled(parmast).then((res: any) => {
    attrKeys.value = res.data_list.map((item: any) => item.attr_key)
    from = res.data_list.map((item: any) => {
      const { attr_key, attr_name, data_type, dict_item_list } = item
      if (dict_item_list) {
        // 如果存在 dict_item_list，则生成 Select 组件
        return {
          component: 'Select',
          componentProps: {
            allowClear: true,
            filterOption: (input, option) => {
              return (option?.label || '').toLowerCase().includes(input.toLowerCase())
            },
            options: Object.entries(dict_item_list).map(([value, label]) => ({
              label,
              value,
            })),
            showSearch: true,
          },
          fieldName: attr_key,
          label: attr_name,
        }
      } else {
        // 根据 data_type 生成对应的组件
        if (data_type.includes('input-number')) {
          return {
            component: 'InputNumber',
            componentProps: {
              min: 0,
              precision: item.attr?.precision || 2,
              step: item.attr?.step || 1,
              stringMode: false,
            },
            fieldName: attr_key,
            label: attr_name,
          }
        } else if (data_type.includes('textarea')) {
          return {
            component: 'Textarea',
            componentProps: {
              allowClear: true,
              class: 'w-full',
            },
            fieldName: attr_key,
            label: attr_name,
          }
        } else {
          return {
            component: 'Input',
            componentProps: {
              allowClear: true,
              class: 'w-full',
            },
            fieldName: attr_key,
            label: attr_name,
          }
        }
      }
    })

    baseFormApi.setState((prev) => {
      return {
        schema: [...schema.value, ...from],
      }
    })
  })
}

interface RowType {
  is_default: boolean
  jg_price: string
  id: number
  plan_id: number
  purchase_price: string
  supply_id: number
}
const gridOptions: VxeTableGridOptions<RowType> = {
  columns: [
    { field: 'supply_id', title: '供货商', slots: { default: 'supply_id' } },
    {
      field: 'purchase_price',
      title: '采购价',
      slots: { default: 'purchase_price' },
    },
    { field: 'jg_price', title: '加工费', slots: { default: 'jg_price' } },
    {
      field: 'is_default',
      title: '默认供应商',
      slots: { default: 'is_default' },
    },
    {
      field: 'action',
      title: '操作',
      fixed: 'right',
      width: 110,
      slots: { default: 'action' },
    },
  ],
  data: [],
  pagerConfig: {
    enabled: false,
  },
  sortConfig: {
    multiple: true,
  },
}
const [Grid, gridApi] = useVbenVxeGrid({ gridOptions })

// 获取供应商列表
// 1) 远程下拉数据
const supplyOptions = ref<{ label: string; value: number }[]>([])
const supplyLoading = ref(false)

const handleSupplySearch = useDebounceFn(async (keyword: string) => {
  supplyLoading.value = true
  try {
    const { list } = await getFactoryIndex({
      quick_search: keyword || '',
      page: 1,
      limit: 9999,
      initKey: 'id',
      select: true,
    })
    supplyOptions.value = list.map((it: any) => ({
      label: it.SupplyNa,
      value: it.id,
    }))
  } finally {
    supplyLoading.value = false
  }
}, 300)

// 第一次打开下拉就触发一次空搜索，把全部选项拿回来
const handleSupplyDropdown = (open: boolean) => {
  if (open && supplyOptions.value.length === 0) {
    handleSupplySearch('')
  }
}

function handleIsDefaultChange(row: RowType) {
  // 如果当前行的 is_default 被设置为 true，则将其他行的 is_default 设置为 false
  if (row.is_default) {
    const tableData = gridApi.grid.getData()
    // 更新数据
    const updatedData = tableData.map((item) => {
      if (item.id !== row.id) {
        return { ...item, is_default: false } // 其他行的 is_default 设置为 false
      }
      return item // 当前行保持不变
    })
    gridApi.setGridOptions({ data: updatedData })
  }
}

function dleSupply(row: RowType) {
  // 获取当前表格的数据
  const tableData = gridApi.grid.getData()

  // 找到需要删除的行索引
  const rowIndex = tableData.findIndex((item) => item.id === row.id)
  // 如果找到了对应的行，则从数据中移除该行
  if (rowIndex !== -1) {
    tableData.splice(rowIndex, 1)
    // 更新表格数据
    gridApi.setGridOptions({ data: tableData })
    message.success({ content: '删除成功' })
  }
}

function addSupply() {
  // 创建一个新的行数据对象
  const newRow: any = {
    id: '', // 使用时间戳作为唯一的 ID
    supply_id: null,
    purchase_price: null,
    jg_price: null,
    is_default: false,
    plan_id: 0,
  }

  // 获取当前表格的数据
  const tableData = gridApi.grid.getData()
  // 将新行数据添加到表格数据中
  tableData.push(newRow)
  // 更新表格数据以刷新视图
  gridApi.setGridOptions({ data: tableData })
  message.success({ content: '添加成功' })
}

// 关闭弹窗
async function handleFilePushData(data: any) {
  // 获取当前表单中已有的ingr_images值
  const currentValues: any = await baseFormApi.getValues()
  const existingImages = currentValues.ingr_images || []
  const newUrls = data.map((item) => item.full_url)
  const mergedImages = [...existingImages, ...newUrls]
  // 更新表单数据
  await baseFormApi.setValues({ ingr_images: mergedImages })

  // 更新ingrImages变量，用于模板渲染
  ingrImages.value = mergedImages
  // 显示成功提示
  message.success('文件已添加')
}
const UpdatafileList = ref([])
const existingImages = ref([])
async function addingrImages(data: any, url: any) {
  const newUrls = url.map((item: any) => item.url)
  const mergedImages = [...existingImages.value, ...newUrls]
  await baseFormApi.setValues({ ingr_images: mergedImages })
  ingrImages.value = mergedImages
}

// 删除标签
function handleRemoveTag(index: number) {
  // 创建新数组，排除要删除的项
  const newImages = ingrImages.value.slice(0, index)

  // 更新响应式变量
  ingrImages.value = newImages

  // 更新表单字段
  baseFormApi.setValues({
    ingr_images: newImages,
  })

  // 显示成功提示
  message.success('文件已移除')
}
// 预览文件
function openFile(url: string) {
  window.open(url)
}
// 选择文件
const [FileListModal, FileListModalApi] = useVbenModal({
  connectedComponent: FileList,
})

function openList() {
  FileListModalApi.setData({}).open()
}

// 添加提交审批弹窗
const [submitApprovalModal, submitApprovalModalApi] = useVbenModal({
  connectedComponent: submitApproval,
})
// 提交审批回来
function submitAppr(data: any) {
  baseFormApi.setValues({ is_confirm_price_update: true }, false)
  baseFormApi.setValues({ create_approval_text: data }, false)
  save()
}
</script>

<template>
  <Modal :title="currentView === 'edit' ? '编辑' : currentView === 'add' ? '新建' : '拷贝'">
    <Page content-class="flex flex-col gap-4" description="" title="">
      <BaseForm>
        <template #_divider>
          <Divider orientation="left">基础信息</Divider>
        </template>
        <template #goods_images>
          <Row style="height: 200px; width: 100%; overflow-y: auto">
            <Col span="24">
              <ImageUploader v-model:value="goodsImages" :multiple="true" accept=".jpg,.jpeg,.png,.gif" :max-count="9" upload-text="上传货品图片" />
            </Col>
          </Row>
        </template>
        <template #ingr_images>
          <Row style="height: 200px; width: 100%">
            <Col span="24">
              <div>
                <Space>
                  <adapterFileLists v-model:file-list="UpdatafileList" :multiple="true" @upload-success="(url) => addingrImages(UpdatafileList, url)" />
                  <Button type="primary" @click="openList()">选择</Button>
                </Space>
              </div>
              <template v-if="ingrImages && ingrImages.length > 0">
                <div style="max-height: 200px; overflow-y: auto; padding: 8px 0">
                  <div v-for="(url, index) in ingrImages" :key="index" style="margin-bottom: 4px">
                    <Tag @click="openFile(url)" closable @close="handleRemoveTag(index)">
                      {{ url.split('/').pop() }}
                    </Tag>
                  </div>
                </div>
              </template>
            </Col>
          </Row>
        </template>
        <template #_divider1>
          <Divider orientation="left">基础信息</Divider>
        </template>
        <template #_divider2>
          <Divider orientation="left">分类信息</Divider>
        </template>
        <template #_divider3>
          <Divider orientation="left">
            价格信息
            <span style="color: red" v-if="is_price_checking">【有价格正在审核中,审核期间资料价格和供应商价格不允许再次修改！！！！！】</span>
          </Divider>
        </template>
        <template #_divider4>
          <Divider orientation="left">供应商当前价格信息</Divider>
        </template>
        <template #but>
          <div style="width: 100%">
            <div style="width: 100%; display: flex; justify-content: flex-end">
              <Button type="primary" size="small" @click="addSupply()"> 添加 </Button>
            </div>
            <Grid>
              <template #supply_id="{ row }">
                <Select
                  v-model:value="row.supply_id"
                  show-search
                  allow-clear
                  placeholder="请输入供应商关键词"
                  :filter-option="false"
                  :options="supplyOptions"
                  :loading="supplyLoading"
                  @search="handleSupplySearch"
                  @dropdown-visible-change="handleSupplyDropdown"
                  style="width: 100%"
                />
              </template>
              <template #purchase_price="{ row }">
                <InputNumber min="0" step="1" :disabled="is_price_checking" style="width: 100%" placeholder="请输入采购价" v-model:value="row.purchase_price" />
              </template>
              <template #jg_price="{ row }">
                <InputNumber min="0" step="1" style="width: 100%" placeholder="请输入加工费" v-model:value="row.jg_price" />
              </template>
              <template #is_default="{ row }">
                <Switch v-model:checked="row.is_default" @change="() => handleIsDefaultChange(row)" />
              </template>
              <template #action="{ row }">
                <Button type="primary" danger size="small" @click="dleSupply(row)"> 删除 </Button>
              </template>
            </Grid>
          </div>
        </template>
        <template #_divider5>
          <Divider orientation="left">属性信息</Divider>
        </template>
      </BaseForm>
      <FileListModal @push-data="handleFilePushData" />
      <submitApprovalModal @push-data="submitAppr" />
    </Page>
  </Modal>
</template>

<style scoped>
/* 让 Form.Item 不再有默认 margin-bottom */
.mb-0 {
  margin-bottom: 0 !important;
}
</style>
